﻿using Autofac;
using KJSync.Access.Models;
using KJSyncXP.Access.Context;
using KJSyncXP.Extensions;
using KJSyncXP.Oracle.Context;
using KJSyncXP.SQLite.Context;
using KJSyncXP.Sqlite.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.IO;

namespace KJSyncXP.Services
{
    public class SqliteToFileSyncService
    {
        private readonly log4net.ILog _logger;

        private readonly AppConfig _appConfig;

        private const string __REMOTE_SYNC_STATE_PENDING = "PENDING";

        private const string __REMOTE_SYNC_STATE_COMPLETE = "COMPLETE";

        private readonly IdFileManager _idFileManager;

        private readonly SqliteDbContext _sqliteCtx;
        ///<summary>
        /// 构造函数
        /// </summary>
        public SqliteToFileSyncService(log4net.ILog log, AppConfig appConfig,IdFileManager idFileManager, SqliteDbContext sqliteCtx)
        {
            _logger = log;
            _appConfig = appConfig;
            _idFileManager = idFileManager;
            _sqliteCtx = sqliteCtx;
        }


        /// <summary>
        /// 从Sqlite拉取同步标准数据处理文件,反写oracle和sqlite,同时还要记录标准变更日志数据
        /// </summary>

        public void PullTestStandardToFile()
        {
            /*var scope = App._container.BeginLifetimeScope();
            var sqliteCtx = scope.Resolve<SqliteDbContext>();
            var oracleCtx = scope.Resolve<OracleDbContext>();
            var accsseCtx = scope.Resolve<AccessDbContext>();*/

            try
            {
                //查询Sqlite中 KJ_TEST_STANDARD中所有还未同步的标准数据
                var sqliteTestStandards = _sqliteCtx.Db.Queryable<Sqlite_KJ_TEST_STANDARD>().
                    Where(item => item.RECEIVE_FLAG == __REMOTE_SYNC_STATE_PENDING).ToList();


                if (!sqliteTestStandards.Any())
                {
                    _logger.Warn("SQLite的KJ_TEST_STANDARD表中无数据，无需处理");
                    return;
                }

                // 按物料分组
                var materialGroups = sqliteTestStandards
                    .GroupBy(standard => standard.PART_NUMBER) // 按物料编号分组
                    .ToList();

                // 遍历每个物料组，处理多条数据
                foreach (var group in materialGroups)
                {
                    string materialCode = group.Key; // 当前物料编号
                    var materialDataList = group.ToList(); // 该物料的所有数据

                    //  查出所有TEST_PROJECT = MH
                    var MHList = materialDataList.Where(item => item.TEST_PROJECT == "MH").ToList();
                    //  查出所有TEST_PROJECT = MH
                    var TC30List = materialDataList.Where(item => item.TEST_PROJECT == "TC30").ToList();
                    //  查出所有TEST_PROJECT = MH
                    var TC90List = materialDataList.Where(item => item.TEST_PROJECT == "TC90").ToList();

                    //所有新增是需要处理的数据
                    // 文件名
                    var fileName = group.Key;
                    // 车次
                    var checiNumber = "1";
                    // 班组
                    var shift = "A";
                    // 批号
                    var lotNumber = "";
                    // 机台号
                    var machineNumber = _appConfig.DetectionMachineNo;
                    // MH标准
                    var mhString = GetMHString(MHList);
                    // TC30标准
                    var tc30String = GetTCString("30",TC30List);
                    // TC90标准
                    var tc90String = GetTCString("90",TC90List);
                    // 工号
                    var userCode = "admin";
                  
                    _idFileManager.CreateNewFile(fileName,checiNumber,shift,lotNumber,machineNumber,
                        mhString,tc30String,tc90String,userCode,MHList, TC30List, TC90List);

                    // 修改中间表状态
                    _sqliteCtx.Db.Update<Sqlite_KJ_TEST_STANDARD>()
                            .SetSource(sqliteTestStandards,item=>item.GUID) // 待更新的数据源
                            .Set(item=>item.RECEIVE_FLAG ,__REMOTE_SYNC_STATE_COMPLETE)
                            .Set(item => item.RECEIVE_DATE,DateTime.Now)
                            .ExecuteAffrows();
                };
            }
            catch (Exception ex)
            {

                _logger.Error("同步标准到access异常", ex);
            }
           
        }


        public string GetMHString(List<Sqlite_KJ_TEST_STANDARD> MHList)
        {
            if (MHList == null || !MHList.Any())
            {
                // 无数据时返回默认空格式（7个空值用/分隔）
                return "//////";
            }

            // A类
            var classA = MHList.Where(item=>item.TEST_TYPE =="A").FirstOrDefault();
            // B类
            var classB = MHList.Where(item => item.TEST_TYPE == "B").FirstOrDefault();
            // C类
            var classC = MHList.Where(item => item.TEST_TYPE == "C").FirstOrDefault();

            // 提取各字段值（处理null值，转为空字符串）
            string aUpper = classA.MAX_DATA?.ToString() ?? "";
            string aLower = classA.MIN_DATA?.ToString() ?? "";
            string aPosition = "0";
            string bUpper = classB.MAX_DATA?.ToString() ?? "";
            string bLower = classB.MIN_DATA?.ToString() ?? "";
            string cUpper = classC.MAX_DATA?.ToString() ?? "";
            string cLower = classC.MIN_DATA?.ToString() ?? "";

            // 按格式拼接（A上限/A下限/A位置/B上限/B下限/C上限/C下限）
            return $"{aUpper}/{aLower}/{aPosition}/{bUpper}/{bLower}/{cUpper}/{cLower}";
        }

        public string GetTCString(string projectName , List<Sqlite_KJ_TEST_STANDARD> TCList)
        {
            if (TCList == null || !TCList.Any())
            {
                // 无数据时返回默认空格式（8个空值用/分隔）
                return "///////";
            }
            // A类
            var classA = TCList.Where(item => item.TEST_TYPE == "A").FirstOrDefault();
            // B类
            var classB = TCList.Where(item => item.TEST_TYPE == "B").FirstOrDefault();
            // C类
            var classC = TCList.Where(item => item.TEST_TYPE == "C").FirstOrDefault();

            // 提取各字段值（处理null值，转为空字符串）
            string aUpper = classA.MAX_DATA?.ToString() ?? "";
            string aLower = classA.MIN_DATA?.ToString() ?? "";
            string aPosition = "0";
            string bUpper = classB.MAX_DATA?.ToString() ?? "";
            string bLower = classB.MIN_DATA?.ToString() ?? "";
            string cUpper = classC.MAX_DATA?.ToString() ?? "";
            string cLower = classC.MIN_DATA?.ToString() ?? "";

            // 按格式拼接：项目名称/A上限/A下限/A位置/B上限/B下限/C上限/C下限
            return $"{projectName}/{aUpper}/{aLower}/{aPosition}/{bUpper}/{bLower}/{cUpper}/{cLower}";
        }



        /// <summary>
        /// 手动修改标准文件
        /// </summary>
        public void ManualModifyFile(string fileName)
        {
            //读取历史文件
            var oldpath = fileName + ".bak";
            var oldContent = _idFileManager.GetFileContent(oldpath);
            //读取新文件
            var newpath = fileName + ".id";
            var newContent = _idFileManager.GetFileContent(newpath);

            //记录的主表
            List<FileChangeRecords> fileChangeRecord = new List<FileChangeRecords>();
            //记录的行表
            List<FileChangeRecordsItem> fileChangeRecordItem = new List<FileChangeRecordsItem>();

            var criticalIndexes = new List<int>
                {
                    /*IdFileManager.checiNumberIndex,
                    IdFileManager.shiftIndex,
                    IdFileManager.machineNumberIndex,
                    IdFileManager.lotNumberIndex,*/
                    IdFileManager.mhStringIndex,
                    /*IdFileManager.tc30StringIndex,
                    IdFileManager.tc90StringIndex,
                    IdFileManager.userCodeIndex*/
                };

            // 遍历每个关键行索引，检查差异
            foreach (int index in criticalIndexes)
            {
                string oldLine = oldContent[index];
                string newLine = newContent[index];
                string[] oldParts = oldLine.Split('/');
                string[] newParts = newLine.Split('/');


                if (oldLine != null && newLine != null && !string.Equals(oldLine, newLine, StringComparison.Ordinal))
                {
                    if (index == IdFileManager.mhStringIndex)
                    {
                        var diffindex = new List<int>();
                        for (int i = 0; i < newParts.Length; i++)
                        {
                            string oldPart = oldParts[i]; 
                            string newPart = newParts[i];

                            // 比较对应位置的值是否不同
                            if (!string.Equals(oldPart, newPart, StringComparison.Ordinal))
                            {
                                diffindex.Add(i);
                            }                          
                        }

                        if (diffindex.Contains(0) || diffindex.Contains(1))
                        {
                            var record = new FileChangeRecords()
                            {
                                Guid = Guid.NewGuid(),
                                TestType = "A",
                                PartNumber = fileName,
                                MachineNumber = _appConfig.DetectionMachineNo,
                                UpdateDate = DateTime.Now,
                                Type = "Local"
                            };
                            var recorditem = new FileChangeRecordsItem()
                            {
                                ItemGuid = record.Guid,
                                Name = "Mh",
                                OldMax = decimal.Parse(oldParts[0]),
                                OldMin = decimal.Parse(oldParts[1]),   
                                NewMax = decimal.Parse(newParts[0]),
                                NewMin = decimal.Parse(newParts[1]),
                            };

                            fileChangeRecord.Add(record);
                            fileChangeRecordItem.Add(recorditem);
                        }

                    }

                }
            }

            _sqliteCtx.Db.Insert<FileChangeRecords>(fileChangeRecord).ExecuteAffrows();
            _sqliteCtx.Db.Insert<FileChangeRecordsItem>(fileChangeRecordItem).ExecuteAffrows();

        }

    }
}
